import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class HttpDemo extends StatefulWidget {
  @override
  _HttpDemoState createState() {
    return _HttpDemoState();
  }
}

class _HttpDemoState extends State<HttpDemo> {
  @override
  void initState() {
    super.initState();
    /*
    * json  和 实体类的转换
    *  默认是 map的转换
    *
    * */
    var post = PostMode("title1", "描述", "1", "http://ss/ss.png");
    // print(json.encode(post));
    _fecthData().whenComplete((){
      print("whenComplete ");
    }).then((json){
      print("then ${json}");
    });


  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return FutureBuilder(

      future: _fecthData(),
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
        if(snapshot.hasData){
          final  List<PostMode> datas=snapshot.data;
          return ListView.builder(itemBuilder: (context,index){
            print(datas[index].imageUrl);
            return  ListTile(
              leading: Image.network(datas[index].imageUrl),
              title: Text(datas[index].title),
              subtitle: Text(datas[index].title,maxLines: 2, overflow: TextOverflow.ellipsis,),

            );

          },itemCount: datas.length,);
        }else {
          return Center(
            child: Text("暂无数据"),
          );
        }

      },
     /* children: [
        ElevatedButton(onPressed: _fecthData, child: Text("get 网络请求")),
      ],*/
    );
  }

  Future<List<PostMode>?> _fecthData() async {
    var url = Uri.parse("https://resources.ninghao.net/demo/posts.json");

    // Await the http get response, then decode the json-formatted response.
    var response = await http.get(url);
    if (response.statusCode == 200) {
      var decodedData = json.decode(response.body); // 保存解码结果
      print('解码后的数据: $decodedData');
      print('解码后的数据: ${decodedData["posts"][0]["id"]}');

      List<PostMode> realDatas = decodedData['posts'].map<PostMode>((it) {
        return PostMode.fromJson1(it);
      }).toList();
      return realDatas;
    } else {
      print('Request failed with status: ${response.statusCode}.');
    }
  }
}

class PostMode {
  final String title;
  final String description;
  final String id;
  final String imageUrl;

  PostMode(this.title, this.description, this.id, this.imageUrl);


  Map<String, dynamic> toJson() {
    return {
      'title': title,
      'description': description,
      'id': id,
      'imageUrl': imageUrl,
    };
  }

  PostMode.fromJson(Map<String, dynamic> json)
      : id = json['id'],
        title = json['title'],
        description = json['description'],
        imageUrl = json['imageUrl'];

  factory PostMode.fromJson1(Map<String, dynamic> json) {
    return PostMode(
        json['title'] ?? '',
        json['description'] ?? '',
        (json['id'] ?? '').toString(),
        json['imageUrl'] ?? '');
  }
  }
